﻿using Core.Tools.IOC;
using Prism.Events;
using Prism.Modularity;
using Prism.Regions;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using UI.Application.Initialize.Services;
using UI.Application.Share.Names;

namespace UI.Application.Initialize.ViewModels
{
    internal class InitializeViewModel : ReactiveObject
    {
        private HardwareManager HardwareManager { get; }

        /// <summary>
        /// 前端显示加载信息
        /// </summary>
        [Reactive]
        public string Message { get; set; } = string.Empty;

        [Reactive]
        public Visibility ButtonVisibility { get; set; } = Visibility.Collapsed;

        public ICommand InitCommand { get; }
        public ICommand EnterCommand { get; }

        public InitializeViewModel(HardwareManager hardwareManager)
        {
            InitCommand = ReactiveCommand.Create(InitAsync);
            EnterCommand = ReactiveCommand.Create(Enter);
            HardwareManager = hardwareManager;
        }

        private async void InitAsync()
        {
            ButtonVisibility = Visibility.Collapsed;

            if (!HardwareManager.Initialized)
            {
                Message = "正在初始化硬件";

                var result = await HardwareManager.InitAsync();

                if(!result.Success)
                {
                    Message= result.Message;
                    ButtonVisibility= Visibility.Visible;
                    return;
                }

            }

            Message = "初始化完成";

            Enter();
        }

        private async void Enter()
        {
            await Task.Delay(250).ContinueWith(p =>
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    PrismProvider.ModuleManager.LoadModule(ModuleNames.ApplicationMainModule);
                    PrismProvider.RegionManager.RequestNavigate(RegionNames.MainRegion, ViewNames.MainView);
                });
            });
        }
    }
}
